import axios from 'axios'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export const useUserStore = defineStore('user', () =>
{
  // 状态
  const user = ref(null)
  const token = ref(localStorage.getItem('token') || '')
  const isLoggedIn = computed(() => !!token.value && !!user.value)

  // 设置token
  const setToken = (newToken) =>
  {
    token.value = newToken
    if (newToken)
    {
      localStorage.setItem('token', newToken)
      axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`
    } else
    {
      localStorage.removeItem('token')
      delete axios.defaults.headers.common['Authorization']
    }
  }

  // 设置用户信息
  const setUser = (userInfo) =>
  {
    // 确保用户信息字段完整
    if (userInfo)
    {
      user.value = {
        id: userInfo.id,
        username: userInfo.username,
        email: userInfo.email,
        nickname: userInfo.nickname,
        avatarUrl: userInfo.avatarUrl,
        phone: userInfo.phone,
        bio: userInfo.bio,
        loginType: userInfo.loginType,
        status: userInfo.status,
        role: userInfo.role,
        loginCount: userInfo.loginCount,
        scriptGenerationCount: userInfo.scriptGenerationCount,
        templateCreationCount: userInfo.templateCreationCount,
        lastLoginTime: userInfo.lastLoginTime,
        lastActiveTime: userInfo.lastActiveTime,
        profileCompletion: userInfo.profileCompletion,
        preferences: userInfo.preferences,
        emailVerified: userInfo.emailVerified,
        phoneVerified: userInfo.phoneVerified,
        createdAt: userInfo.createdAt,
        updatedAt: userInfo.updatedAt
      }
    } else
    {
      user.value = null
    }
  }

  // 登录
  const login = async (loginData) =>
  {
    try
    {
      const response = await axios.post('/auth/login', loginData)
      if (response.data.code === 200)
      {
        const { token: newToken, user: userInfo } = response.data.data
        setToken(newToken)
        setUser(userInfo)
        ElMessage.success('登录成功')

        // 更新登录统计
        try
        {
          // 开源版本跳过登录统计API调用
          const isOpenSourceVersion = true // 开源版本标识
          if (isOpenSourceVersion)
          {
            console.debug('📊 开源版本跳过登录统计API调用')
          } else
          {
            const statsResponse = await axios.post('/user/login-stats')
            console.debug('登录统计更新成功')
          }
        } catch (statsError)
        {
          console.warn('更新登录统计失败:', statsError.message)
        }

        return { success: true, data: response.data.data }
      } else
      {
        throw new Error(response.data.message || '登录失败')
      }
    } catch (error)
    {
      const message = error.response?.data?.message || error.message || '登录失败'
      ElMessage.error(message)
      return { success: false, message }
    }
  }

  // 注册
  const register = async (registerData) =>
  {
    try
    {
      const response = await axios.post('/auth/register', registerData)
      if (response.data.code === 200)
      {
        ElMessage.success('注册成功，请登录')
        return { success: true, data: response.data.data }
      } else
      {
        throw new Error(response.data.message || '注册失败')
      }
    } catch (error)
    {
      const message = error.response?.data?.message || error.message || '注册失败'
      ElMessage.error(message)
      return { success: false, message }
    }
  }

  // 获取当前用户信息
  const getCurrentUser = async () =>
  {
    try
    {
      if (!token.value)
      {
        console.log('getCurrentUser: 没有token')
        return { success: false, message: '未登录' }
      }

      console.log('getCurrentUser: 发送请求获取用户信息...')
      const response = await axios.get('/auth/me')
      console.log('getCurrentUser: 响应', response.data)

      if (response.data.code === 200)
      {
        setUser(response.data.data)
        console.log('getCurrentUser: 用户信息设置成功', response.data.data)
        return { success: true, data: response.data.data }
      } else
      {
        throw new Error(response.data.message || '获取用户信息失败')
      }
    } catch (error)
    {
      console.error('getCurrentUser: 错误', error)

      // 如果token无效，清除登录状态
      if (error.response?.status === 401)
      {
        console.log('getCurrentUser: token无效，清除登录状态')
        logout()
      }
      return { success: false, message: error.message || '获取用户信息失败' }
    }
  }

  // 刷新token
  const refreshToken = async () =>
  {
    try
    {
      if (!token.value) return { success: false, message: '未登录' }

      const response = await axios.post('/auth/refresh')
      if (response.data.code === 200)
      {
        const { token: newToken, user: userInfo } = response.data.data
        setToken(newToken)
        setUser(userInfo)
        return { success: true, data: response.data.data }
      } else
      {
        throw new Error(response.data.message || 'Token刷新失败')
      }
    } catch (error)
    {
      logout()
      return { success: false, message: error.message }
    }
  }

  // 登出
  const logout = () =>
  {
    setToken('')
    setUser(null)
    ElMessage.success('已退出登录')
  }

  // 更新用户信息
  const updateUser = async (userData) =>
  {
    try
    {
      const response = await axios.put(`/users/${user.value.id}`, userData)
      if (response.data.code === 200)
      {
        setUser(response.data.data)
        ElMessage.success('用户信息更新成功')
        return { success: true, data: response.data.data }
      } else
      {
        throw new Error(response.data.message || '更新失败')
      }
    } catch (error)
    {
      const message = error.response?.data?.message || error.message || '更新失败'
      ElMessage.error(message)
      return { success: false, message }
    }
  }

  // 检查登录状态
  const checkLoginStatus = async () =>
  {
    try
    {
      if (!token.value)
      {
        return false
      }

      const response = await axios.get('/auth/me')
      if (response.data.code === 200)
      {
        setUser(response.data.data)
        return true
      } else
      {
        // token无效，清除登录状态
        logout()
        return false
      }
    } catch (error)
    {
      // token无效或网络错误，清除登录状态
      logout()
      return false
    }
  }

  // 初始化用户状态
  const initializeUserState = async () =>
  {
    // 如果有token但没有用户信息，尝试获取用户信息
    if (token.value && !user.value)
    {
      console.log('初始化用户状态：发现token，尝试获取用户信息...')
      try
      {
        const result = await getCurrentUser()
        if (result.success)
        {
          console.log('初始化用户状态：用户信息获取成功', result.data)
        } else
        {
          console.log('初始化用户状态：用户信息获取失败，清除token')
          logout()
        }
      } catch (error)
      {
        console.error('初始化用户状态：获取用户信息异常', error)
        logout()
      }
    }
  }

  // 初始化时设置token到axios header
  if (token.value)
  {
    axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
    // 延迟初始化用户状态，避免阻塞应用启动
    setTimeout(initializeUserState, 100)
  }

  // 记录用户活动
  const recordActivity = async (activityType, activityData = null) =>
  {
    try
    {
      if (!isLoggedIn.value)
      {
        console.log('用户未登录，跳过活动记录')
        return { success: true, message: '跳过活动记录（用户未登录）' }
      }

      console.log('准备记录用户活动:', activityType, activityData)
      const response = await axios.post('/user/activity', activityData, {
        params: { activityType }
      })

      if (response.data.code === 200)
      {
        console.log('活动记录成功:', activityType, activityData)
        return { success: true }
      } else
      {
        console.warn('活动记录失败:', response.data.message)
        return { success: false, message: response.data.message }
      }
    } catch (error)
    {
      console.warn('记录用户活动失败:', error.message)
      return { success: false, message: error.message }
    }
  }

  // 记录软件选择活动
  const recordSoftwareSelection = async (softwareName, action) =>
  {
    try
    {
      if (!isLoggedIn.value)
      {
        console.log('用户未登录，跳过软件选择活动记录')
        return { success: true, message: '跳过活动记录（用户未登录）' }
      }

      console.log('准备记录软件选择活动:', action, softwareName)
      const response = await axios.post('/software/selection-activity', null, {
        params: {
          softwareName,
          action
        }
      })

      if (response.data.code === 200)
      {
        console.log('软件选择活动记录成功:', action, softwareName)
        return { success: true }
      } else
      {
        console.warn('软件选择活动记录失败:', response.data.message)
        return { success: false, message: response.data.message }
      }
    } catch (error)
    {
      console.warn('记录软件选择活动失败:', error.message)
      return { success: false, message: error.message }
    }
  }

  return {
    // 状态
    user,
    token,
    isLoggedIn,

    // 方法
    login,
    register,
    getCurrentUser,
    refreshToken,
    logout,
    updateUser,
    checkLoginStatus,
    setToken,
    setUser,
    initializeUserState,
    recordActivity,
    recordSoftwareSelection
  }
})
